<template>
  <div class="consultation-records-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">看诊记录管理</span>
          <div class="toolbar">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增记录</el-button>
            <el-button
                type="danger"
                :icon="Delete"
                :disabled="!multipleSelection.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
          v-loading="loading"
          :data="visits"
          stripe
          border
          height="calc(100vh - 280px)"  style="width: 100%;"
          @selection-change="handleSelectionChange"
          class="custom-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="visitId" label="编号" width="80" align="center" />
        <el-table-column prop="userId" label="患者ID" width="100" align="center" />
        <el-table-column prop="doctorId" label="医生ID" width="100" align="center" />
        <el-table-column prop="hospitalId" label="医院ID" width="100" align="center" />
        <el-table-column prop="visitDate" label="就诊日期" width="170" sortable> <template #default="{ row }">
          {{ formatDateTime(row.visitDate) }}
        </template>
        </el-table-column>
        <el-table-column prop="diagnosis" label="诊断" min-width="180" show-overflow-tooltip />
        <el-table-column prop="prescription" label="处方" min-width="180" show-overflow-tooltip />
        <el-table-column prop="notes" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="created" label="创建时间" width="170" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.created) }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="100"
            fixed="right"
            align="center"
        >
          <template #default="scope">
            <el-button
                link
                type="danger"
                :icon="Delete"
                @click="handleDelete(scope.row.visitId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue' // 导入图标

const router = useRouter() // 获取路由实例

const visits = ref([])
const loading = ref(true)
const multipleSelection = ref([])

// 格式化日期时间函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  if (isNaN(date.getTime())) return dateTimeString; // 如果是无效日期，直接返回原字符串

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const fetchVisits = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/visits')
    // 确保 res.data.data 是一个数组，或者至少能处理非数组情况
    visits.value = Array.isArray(res.data.data) ? res.data.data : (res.data.data ? [res.data.data] : []);
    ElMessage.success('看诊记录获取成功！');
  } catch (error) {
    console.error('获取看诊记录失败', error)
    ElMessage.error('获取看诊记录失败，请检查网络或服务器。')
  } finally {
    loading.value = false
  }
}

// 新增看诊记录
const handleAdd = () => {
  router.push('/home/add_consultation') // 假设新增页面路径
}

// 删除单个记录
const handleDelete = (id) => {
  ElMessageBox.confirm(
      '此操作将永久删除该记录，是否继续？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await axios.delete(`http://localhost:8080/visits/${id}`)
          ElMessage.success('删除成功！')
          fetchVisits() // 重新加载数据
        } catch (error) {
          console.error('删除失败', error)
          ElMessage.error('删除失败，请稍后再试。')
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除。')
      })
}

// 多选删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条记录进行删除。');
    return;
  }
  ElMessageBox.confirm(
      `确定要批量删除选中的 ${multipleSelection.value.length} 条记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          // 收集所有选中记录的ID
          const idsToDelete = multipleSelection.value.map(item => item.visitId);
          // 发送批量删除请求 (如果后端支持)
          // 假设后端有一个 /visits/batchDelete 接口接收一个ID数组
          // await axios.post('http://localhost:8080/visits/batchDelete', { ids: idsToDelete });
          // 如果后端只支持单条删除，则循环调用删除接口
          await Promise.all(
              idsToDelete.map(id => axios.delete(`http://localhost:8080/visits/${id}`))
          )
          ElMessage.success('批量删除成功！')
          fetchVisits() // 重新加载数据
          multipleSelection.value = []; // 清空选中项
        } catch (error) {
          console.error('批量删除失败', error)
          ElMessage.error('批量删除失败，请稍后再试。')
        }
      })
      .catch(() => {
        ElMessage.info('已取消批量删除。')
      })
}

// 表格多选变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

onMounted(() => {
  fetchVisits()
})
</script>

<style scoped>
.consultation-records-container {
  padding: 30px; /* 页面内边距 */
  background-color: #f8fbfd; /* 页面背景色 */
  min-height: calc(100vh - 60px); /* 适应主布局高度 */
}

.box-card {
  border-radius: 12px; /* 圆角卡片 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08); /* 柔和阴影 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5; /* 分隔线 */
  margin-bottom: 20px;
}

.card-title {
  font-size: 24px; /* 标题字号 */
  font-weight: bold;
  color: #333;
}

.toolbar {
  display: flex;
  gap: 12px; /* 按钮间距 */
}

.toolbar .el-button {
  border-radius: 6px; /* 按钮圆角 */
  padding: 9px 15px; /* 按钮内边距 */
  font-size: 14px;
}

/* 表格样式 */
.custom-table {
  border-radius: 8px; /* 表格圆角 */
  overflow: hidden; /* 确保圆角生效 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 表格轻微阴影 */
}

.custom-table :deep(.el-table__header-wrapper th) {
  background-color: #f2f6fc; /* 表头背景色 */
  color: #555;
  font-weight: 600;
  padding: 12px 0; /* 表头单元格内边距 */
}

.custom-table :deep(.el-table__cell) {
  padding: 10px 0; /* 表格单元格内边距 */
}

/* 操作列按钮 */
.el-button.el-button--link.el-button--danger {
  font-size: 14px;
  padding: 0 5px; /* 链接按钮的内边距 */
}
</style>